package com.eightywork.life.adapter;

import java.util.List;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.eightywork.life.R;
import com.eightywork.life.activity.BaseActivity;
import com.eightywork.life.activity.BrowserActivity;
import com.eightywork.life.activity.ContentActivity;
import com.eightywork.life.activity.ViewImageActivity;
import com.eightywork.life.image.MyImageGetter;
import com.eightywork.life.imageCache.ImageLoader;
import com.eightywork.life.imageCache.ImageLoader.onLoadingFinishListener;
import com.eightywork.life.model.Community;
import com.eightywork.life.service.BaseService;
import com.eightywork.life.service.DoService;
import com.eightywork.life.util.AndroidUtil;
import com.eightywork.life.util.FuncUtil;
import com.eightywork.life.util.MyHttpException;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class MessageListAdapter extends ArrayAdapter<Community> {
	private LayoutInflater mInflater;
	private int mResource = R.layout.item_message_list;
	private Context context;
	private View popView;
	private int width;
	private int height;
	private int popHeight;
	private int popWidth;
	private PopupWindow window;
	private Handler handler = new Handler();
	private ImageLoader imageLoader;
	private MyImageGetter getter;
	private final int[] imagesID = { R.id.image0, R.id.image1, R.id.image2,
			R.id.image3, R.id.image4, R.id.image5 };
	private BaseActivity baseActivity;
	private Dialog dialog;
	private AsyncTask<?, ?, ?> task;

	public MessageListAdapter(Context context, List<Community> list) {
		super(context, 0, list);
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.context = context;
		popView = mInflater.inflate(R.layout.pop_community_more, null);
		width = AndroidUtil.dpToPx(236, context);
		height = AndroidUtil.dpToPx(48, context);
		popHeight = AndroidUtil.dpToPx(72, context);
		popWidth = AndroidUtil.dpToPx(230, context);
		window = new PopupWindow(popView, popWidth, popHeight);
		window.setFocusable(true);
		window.setOutsideTouchable(true);
		window.setBackgroundDrawable(new BitmapDrawable());
		imageLoader = new ImageLoader(getContext());
		getter = new MyImageGetter(context);
		baseActivity = (BaseActivity) context;
	}

	@Override
	public View getView(final int position, View convertView,
			final ViewGroup parent) {
		View layout = convertView;
		if (layout == null) {
			 layout = mInflater.inflate(mResource, parent, false);
		}
		final Community community = getItem(position);
		popView.findViewById(R.id.button_comment).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(context,
								ContentActivity.class);
						intent.putExtra("autoSoftInput", true);
						intent.putExtra("person", "1");
						context.startActivity(intent);
					}
				});

		ImageButton moreButton = (ImageButton) layout
				.findViewById(R.id.button_more);
		moreButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(final View v) {
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						window.showAsDropDown(v, -width, -height);
						ImageButton good = (ImageButton) window
								.getContentView()
								.findViewById(R.id.button_good);
						if (community.getIsshowgood() == 1) {
							good.setSelected(true);
						} else {
							good.setSelected(false);
						}
						good.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								task = new GoodTask().execute(community);
							}
						});
						ImageButton comment = (ImageButton) window
								.getContentView().findViewById(
										R.id.button_comment);
						comment.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								Intent intent = new Intent(context, ContentActivity.class);
								intent.putExtra("isReply", true);
								intent.putExtra("position", position);
								intent.putExtra("idtype", "talkid");
								intent.putExtra("person", "1");
								context.startActivity(intent);
								window.dismiss();
							}
						});
					}
				}, 100);
			}
		});

		View contentText = (View) layout.findViewById(R.id.message_layout);   //这里
		contentText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(context, ContentActivity.class);
				intent.putExtra("position", position);
				intent.putExtra("idtype", "talkid");
				intent.putExtra("person", "1");
				context.startActivity(intent);
			}
		});

		TextView title = (TextView) layout.findViewById(R.id.title);
		if (!community.getTitle().equals("")) {
			title.setText(Html.fromHtml(community.getTitle(), getter, null));
			title.setVisibility(View.VISIBLE);
		} else {
			title.setVisibility(View.GONE);
		}

		TextView content = (TextView) layout.findViewById(R.id.content);
		content.setText(Html.fromHtml(community.getContent(), getter, null));

		TextView name = (TextView) layout.findViewById(R.id.name);
		name.setText(community.getName());

		TextView tag = (TextView) layout.findViewById(R.id.button_type);
		if (community.getTag().equals("")) {
			tag.setVisibility(View.GONE);
		} else {
			tag.setVisibility(View.VISIBLE);
			tag.setText(community.getTag());
		}
		
		TextView time = (TextView) layout.findViewById(R.id.time);
		time.setText(FuncUtil.timeToText(Long.valueOf(community.getDateline()) * 1000));

		// 附件内容
		View appendLayout = layout.findViewById(R.id.append_layout);
		if (!community.getAppend_idtype().equals("")) {
			TextView appendName = (TextView) layout
					.findViewById(R.id.append_name);
			TextView appendTitle = (TextView) layout
					.findViewById(R.id.append_title);
			TextView appendText = (TextView) layout
					.findViewById(R.id.append_text);
			appendName.setText("@" + community.getAppend_name());
			if (!community.getAppend_title().equals("")) {
				appendTitle.setText(community.getAppend_title());
				appendTitle.setVisibility(View.VISIBLE);
				appendText.setVisibility(View.GONE);
			} else {
				appendTitle.setVisibility(View.GONE);
				appendText.setVisibility(View.VISIBLE);
			}
			 appendText.setText(Html.fromHtml(community.getAppend_text(),
			 getter, null));
			ImageView appendImage = (ImageView) layout
					.findViewById(R.id.append_image);
			if (!community.getAppend_link().equals("")) {
				appendLayout.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (community.getAppend_idtype().equals("talkid")) {
							Intent intent = new Intent(context, ContentActivity.class);
							intent.putExtra("position", position);
							intent.putExtra("idtype", "talkid");
							intent.putExtra("isAppend", true);
							intent.putExtra("id", community.getAppend_id());   //**
							intent.putExtra("person", "1");
							context.startActivity(intent);
						} else {
							Intent intent = new Intent(getContext(),
									BrowserActivity.class);
							intent.putExtra("url", BaseService.DOMAIN
									+ community.getAppend_link());
							getContext().startActivity(intent);
						}
					}
				});
			}
			if (community.getAppend_idtype().equals("talkid")) {
				if (community.getAppend_image().equals("")) {
					imageLoader.DisplayImage(community.getAppend_avatar(),
							appendImage, 0, 0, 0);
				} else {
					imageLoader.DisplayImage(community.getAppend_image(),
							appendImage, 0, 0, 0);
				}
			} else {
				imageLoader.DisplayImage(community.getAppend_image(),
						appendImage, 0, 0, 0);
			}
			appendLayout.setVisibility(View.VISIBLE);
		} else {
			appendLayout.setVisibility(View.GONE);
		}

		// 图片内容
		final JsonArray iArray = community.getImages();
		int size = iArray.size();
		for (int i = 0; i < imagesID.length; i++) {
			ImageView imageView = (ImageView) layout.findViewById(imagesID[i]);
			if (size > i) {
				final JsonObject object = iArray.get(i).getAsJsonObject();
				// 只有一张图的话
				if (size == 1 && i == 0) {
					imageLoader.DisplayImage(object.getAsJsonObject()
							.getAsJsonPrimitive("big").getAsString(), 0, 0,
							imageView, new onLoadingFinishListener() {
								@Override
								public void onFinish(Bitmap bitmap,
										ImageView imageView, List<View> list) {
									if (bitmap != null) {
										float h = bitmap.getHeight();
										float w = bitmap.getWidth();
										LayoutParams layoutParams = (LayoutParams) imageView
												.getLayoutParams();
										layoutParams.width = AndroidUtil
												.dpToPx(201, context);
										layoutParams.height = AndroidUtil
												.dpToPx((int) (h / w * 201f),
														context);
										imageView.setImageBitmap(bitmap);
										imageView.setLayoutParams(layoutParams);
									}
								}
							}, null, 0);
				} else {
					imageLoader.DisplayImage(object.getAsJsonPrimitive("small")
							.getAsString(), imageView, 0, 0, R.drawable.pic_1);
					LayoutParams layoutParams = (LayoutParams) imageView
							.getLayoutParams();
					layoutParams.width = AndroidUtil.dpToPx(65, context);
					layoutParams.height = AndroidUtil.dpToPx(65, context);
					imageView.setLayoutParams(layoutParams);
				}

				imageView.setTag(i);
				imageView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(context,
								ViewImageActivity.class);
						intent.putExtra("path",
								BaseService.JsonArrayToStrings(iArray));
						intent.putExtra("pathSmall",
								BaseService.JsonArrayToStringsSmall(iArray));
						intent.putExtra("position", (Integer) v.getTag());
						context.startActivity(intent);
					}
				});
				imageView.setVisibility(View.VISIBLE);
			} else {
				imageView.setVisibility(View.INVISIBLE);
			}
		}

		View layout1 = layout.findViewById(R.id.imageLayout1);
		View layout2 = layout.findViewById(R.id.imageLayout2);
		if (iArray.size() > 0) {
			layout1.setVisibility(View.VISIBLE);
			if (iArray.size() > 3) {
				layout2.setVisibility(View.VISIBLE);
			}
		} else {
			layout1.setVisibility(View.GONE);
			layout2.setVisibility(View.GONE);
		}

		// 赞内容
		TextView showgood = (TextView) layout.findViewById(R.id.showgood);
		JsonArray sgArray = community.getShowgood();
		if (sgArray.size() > 0) {
			StringBuffer sb = new StringBuffer();
			sb.append(" ");
			for (int i = 0; i < sgArray.size(); i++) {
				JsonObject object = sgArray.get(i).getAsJsonObject();
				if (!object.isJsonNull()) {
					JsonElement element = object.get("name");
					if (!element.isJsonNull()) {
						sb.append(element.getAsJsonPrimitive().getAsString());
						if (i < sgArray.size() - 1) {
							sb.append(",");
						}
					}
				}
			}
			showgood.setText(sb.toString());
			showgood.setVisibility(View.VISIBLE);
		} else {
			showgood.setVisibility(View.GONE);
		}

		// 评论内容
		ViewGroup commentLayout = (ViewGroup) layout
				.findViewById(R.id.comment_layout);
		JsonArray cArray = community.getComment();
		commentLayout.removeAllViews();
		if (cArray.size() > 0) {
			TextView count = (TextView) mInflater.inflate(
					R.layout.item_comment_count, null);
			for (int i = 0; i < cArray.size(); i++) {
				View view = mInflater.inflate(R.layout.item_comment, null);
				JsonObject object = cArray.get(i).getAsJsonObject();
				TextView message = (TextView) view.findViewById(R.id.message);
				message.setText(Html.fromHtml(
						object.getAsJsonPrimitive("name").getAsString()
								+ " : "
								+ object.getAsJsonPrimitive("message")
										.getAsString(), getter, null));
				commentLayout.addView(view);
			}
			count.setText("共" + community.getReplynum() + "条评论");
			commentLayout.addView(count);
			commentLayout.setVisibility(View.VISIBLE);
		} else {
			commentLayout.setVisibility(View.GONE);
		}

		ViewGroup reply = (ViewGroup) layout.findViewById(R.id.reply);
		reply.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(context, ContentActivity.class);
				intent.putExtra("isReplyList", true);
				intent.putExtra("position", position);
				intent.putExtra("idtype", "talkid");
				intent.putExtra("person", "1");
				context.startActivity(intent);
			}
		});
		if (showgood.getVisibility() == View.VISIBLE
				|| commentLayout.getVisibility() == View.VISIBLE) {
			reply.setVisibility(View.VISIBLE);
		} else {
			reply.setVisibility(View.GONE);
		}

		View line = (View) layout.findViewById(R.id.line);
		if (showgood.getVisibility() == View.VISIBLE
				&& commentLayout.getVisibility() == View.VISIBLE) {
			line.setVisibility(View.VISIBLE);
		} else {
			line.setVisibility(View.GONE);
		}
		return layout;
	}

	class GoodTask extends AsyncTask<Object, Void, String> {
		Community comm;
		JsonObject object;

		@Override
		protected void onPreExecute() {
			window.dismiss();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Object... params) {
			try {
				String result = "";
				comm = (Community) params[0];
				result = DoService.makeshowgood(comm.getId(), comm.getIdtype());
				object = DoService.showgoodToplist(comm.getId(),
						comm.getIdtype(), "", "");
				return result;
			} catch (MyHttpException e) {
				return e.getErrorMessage();
			}
		}

		@Override
		protected void onPostExecute(String result) {
			if (object != null) {
				comm.setShowgood(object.get("showgoods").getAsJsonArray());
				comm.setIsshowgood(object.get("isshowgood").getAsInt());
				notifyDataSetChanged();
			}
			baseActivity.showMessage(result);
			super.onPostExecute(result);
		}
	}
}
